<template>
  <div>
    <div class="panel">
      <div class="name" v-if="nowItem.type">
        <img :src="require(`../../img/${nowItem.type}.png`)" alt="" />
        <span>{{ nowItem.name }}</span>
        <!-- <TitleTips :src="require(`../../img/${nowItem.type}.png`)" name="标题" tip="我是提示"/> -->
      </div>


      <div class="block">
        <TitleTips name="标题" tip="标题用于告诉填写者应该在该字段中输入什么样的内容。通常是一个词语或词组，也可以是一个问题。"/>
        <div class="content">
          <el-input
            v-model="nowItem.title"
            size="small"
            placeholder="请输入标题"
          ></el-input>
        </div>
      </div>

      <div class="block">
        <TitleTips name="提示" tip="提示属性用于指定对该模块进行一些附加说明，一般用来指导填写者输入。"/>
        <div class="content">
          <el-input
            v-model="nowItem.desc"
            size="small"
            placeholder="请输入提示"
          ></el-input>
        </div>
      </div>

      <div class="block" v-if="nowItem.type == 'select'">
        <TitleTips name="选项内容" tip="我是提示"/>
        <div class="content">
          <div
            v-for="(oi, ok) in nowItem.settings.options"
            :key="ok"
            class="options-relative"
          >
            <el-input v-model="oi.label" type="text" />

            <img
              @click="deleteOption(nowItem.settings.options, ok)"
              v-if="nowItem.settings.options.length > 2"
              src="../../img/delete.png"
              alt=""
            />
            <div
              @click="addOption(nowItem.settings.options)"
              v-show="ok == nowItem.settings.options.length - 1"
              class="fileds-operate fileds-operate-before"
            >
              添加新选项
            </div>
          </div>
        </div>
      </div>

      <div class="block" v-else-if="nowItem.type == 'cascadeChoice'">
        <TitleTips name="选项内容" tip="为选择组件提供具体内容（可以添加“其他”选项，用作选项不符时的自定义填写），可以自定义编辑、增删、批量编辑选项。对选项内容进行修改后，该选项相关的配置同时清空，请在修改选项内容后进行相关修改。"/>
        <div class="content">
          <div
            @click="addCascaderOption()"
            class="fileds-operate fileds-operate-before"
          >
            编辑选项内容
          </div>
        </div>
      </div>

      <div
        class="block"
        v-else-if="nowItem.type == 'time' || nowItem.type == 'timerange'"
      >
        <TitleTips name="显示格式"/>
        <div class="content">
          <el-select
            v-model="nowItem.settings.format"
            class="lpage-form_select"
            filterable=""
            size="small"
          >
            <el-option
              v-for="vi in nowItem.settings.options"
              :key="vi.value"
              :label="vi.label"
              :value="vi.value"
            ></el-option>
          </el-select>
        </div>
      </div>

      <div class="block" v-else-if="nowItem.type == 'file'">
         <TitleTips name="上传文件最大体积" tip="选择后，可以设定文件大小范围，填写者上传超过规定大小的文件时会提示文件大小超过限制，无法上传"/>
        <div class="content content-row">
          <el-input
            v-model="nowItem.settings.limitVolume"
            size="small"
            placeholder="请输入大小"
          ></el-input>
          <span> MB</span>
        </div>
      </div>

      <div class="block">
        <TitleTips name="默认内容" tip="设置默认内容后，默认值会显示在该模块的输入框中，填写者若不做修改，默认值将会作为填写者的数据提交。"/>
        <div class="content">
          <div class="auto-select">
            <el-select
              v-model="nowItem.settings.contentType"
              class="lpage-form_select"
              filterable=""
              size="small"
              :disabled="nowItem.settings.contentDisable"
            >
              <el-option
                v-for="vi in nowItem.settings.contentOptions"
                :key="vi.id"
                :label="vi.name"
                :value="vi.id"
              ></el-option>
            </el-select>
          </div>

          <template v-if="nowItem.type == 'time'">
            <el-date-picker
              v-model="nowItem.settings.value"
              :type="nowItem.settings.formatStatus[nowItem.settings.format]"
              placeholder="选择时间"
              :value-format="nowItem.settings.format"
              :disabled="nowItem.settings.contentType == 'localtime' ? true : false"
              size="small"
            >
            </el-date-picker>
          </template>

          <template v-else-if="nowItem.type == 'timerange'">
            <el-date-picker
              v-model="nowItem.settings.value"
              placeholder="选择时间"
              size="small"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :format="nowItem.settings.format"
               :type="nowItem.settings.formatStatus[nowItem.settings.format]"
            >
            </el-date-picker>
          </template>

          <template v-else-if="nowItem.type == 'textArea'">
            <el-input
              v-model="nowItem.settings.value"
              :readonly="nowItem.settings.contentDisable"
              placeholder="请输入"
              type="textarea"
              @change="changeText"
              size="small"
              :maxlength="nowItem.settings.max"
              :minlength="nowItem.settings.min"
            ></el-input>
          </template>

          <template v-else-if="nowItem.type == 'cascadeChoice'">
            <el-cascader
              size="small"
              v-model="nowItem.settings.value"
              :options="nowItem.settings.cascades"
              :props="{ multiple: nowItem.settings.multiple }"
              :filterable="nowItem.settings.filterable"
              collapse-tags
            ></el-cascader>
          </template>

          <template v-else-if="nowItem.type == 'file'">
            <!-- :on-success="handleAvatarSuccess" -->
            <el-upload
              class="avatar-uploader"
              action=""
              :show-file-list="false"
              :before-upload="checkFile"
              :http-request="uploadSectionFile"
              :limit="
                nowItem.settings.limitNum ? nowItem.settings.limitNum : 99999
              "
            >
              <div class="fileds-operate">上传附件</div>
            </el-upload>
            <div
              class="block-file"
              v-for="(item, index) in nowItem.settings.value"
              :key="item.uid"
              @click="openFile(item)"
            >
              <i class="el-icon-document"></i>
              <span>{{ item.name }}</span>
              <img
                @click="deleteFile(nowItem.settings.value, index)"
                src="../../img/delete.png"
                alt=""
              />
            </div>
          </template>

          <template v-else-if="nowItem.type == 'select'">
            <el-select 
              v-model="nowItem.settings.value" 
              :multiple="nowItem.settings.multiple"
              :filterable="nowItem.settings.filterable" class="lpage-form_select">
              <el-option
                v-for="vi in nowItem.settings.options"
                :key="vi.value"
                :label="vi.label"
                :value="vi.value"
              ></el-option>
            </el-select>
          </template>

          <template v-else>
            <template v-if="nowItem.settings.max && nowItem.settings.min">
              <el-input
                v-model="nowItem.settings.value"
                :disabled="nowItem.settings.contentDisable"
                placeholder="请输入"
                size="small"
                :maxlength="nowItem.settings.max"
                :minlength="nowItem.settings.min"
              ></el-input>
            </template>
            <template v-else>
              <el-input
                v-model="nowItem.settings.value"
                :disabled="nowItem.settings.contentDisable"
                placeholder="请输入"
                size="small"
                
              ></el-input>
            </template>
          </template>
        </div>
      </div>

      <div class="block">
        <el-checkbox text-color="#262A30" v-model="nowItem.settings.required"
          ><TitleTips name="这个是必填项" tip="选择必填后，填写者不填写将无法提交表单"/></el-checkbox
        >
      </div>

      <div class="block" v-if="nowItem.type == 'staticText'">
        <el-checkbox text-color="#262A30" true-label="center" false-label="left" v-model="nowItem.settings.style.textAlign"
          ><TitleTips name="文字居中"   tip="选择文字居中后，该文字进行居中"/></el-checkbox
        >
      </div>

      <template
        v-if="nowItem.type == 'select' || nowItem.type == 'cascadeChoice'"
      >
        <div class="block">
          <el-checkbox @change="changeMultiple" text-color="#262A30" v-model="nowItem.settings.multiple"
            ><TitleTips name="选项可多选" tip="选择多选后，填写者可以选择多个选项"/></el-checkbox
          >
        </div>

        <div class="block">
          <el-checkbox
            text-color="#262A30"
            v-model="nowItem.settings.filterable"
            ><TitleTips name="可搜索选项" tip="选择可搜索后，填写者可以进行搜索筛选"/></el-checkbox
          >
        </div>
      </template>

      <template v-else-if="nowItem.type == 'file'">
        <div class="block">
          <div class="title">
            <el-checkbox
              text-color="#262A30"
              v-model="nowItem.settings.limitNumDis"
              ><TitleTips name="限制文件个数" tip="可以上传的文件数量"/></el-checkbox
            >
          </div>
          <div class="content">
            <el-input
              :placeholder="nowItem.settings.limitNumDis ? '不限' : '请输入'"
              v-model="nowItem.settings.limitNum"
              :disabled="nowItem.settings.limitNumDis"
              type="number"
              size="small"
              clearable
            >
            </el-input>
          </div>
        </div>

        <div class="block">
          <div class="title">
           <TitleTips name="限制文件类型" tip="选择后，可以设定文件类型范围，填写者上传除规定类型外的文件时会提示文件类型错误，无法上传"/>
          </div>
          <div class="content">
            <el-checkbox-group v-model="nowItem.settings.fileSelects">
              <el-checkbox
                border
                v-for="item in nowItem.settings.fileLimits"
                :label="item.name"
                :key="item.type"
                >{{ item.name }}</el-checkbox
              >
              <br />
            </el-checkbox-group>
          </div>
        </div>
      </template>

      <template v-if="nowItem.settings.limitShow">
        <div class="block">
          <div class="title">
            <el-checkbox text-color="#262A30" v-model="nowItem.settings.limit"
              ><TitleTips name="限制字数" tip="字符数"/></el-checkbox
            >
          </div>
          <div class="content" :class="`content-range`">
            <el-input
              :placeholder="nowItem.settings.limit ? '不限' : '请输入最小值'"
              v-model="nowItem.settings.min"
              :disabled="!nowItem.settings.limit"
              clearable
              type="number"
              min="0"
            >
            </el-input>
            <span> - </span>
            <el-input
              :placeholder="nowItem.settings.limit ? '不限' : '请输入最大值'"
              v-model="nowItem.settings.max"
              :disabled="!nowItem.settings.limit"
              clearable
              type="number"
              min="0"
            >
            </el-input>
          </div>
        </div>
      </template>

      <el-dialog
        title="添加选项"
        :visible.sync="showImportCascaderDialogFlag"
        v-if="showImportCascaderDialogFlag"
        :show-close="true"
        class="small-padding-dialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :destroy-on-close="true"
      >
        <CEditor
          v-model="cascadesString"
          mode="json"
          :readonly="false"
        ></CEditor>
        <div slot="footer" class="dialog-footer">
          <el-button
            size="small"
            type=""
            @click="showImportCascaderDialogFlag = false"
            >取消</el-button
          >

          <el-button size="small" type="primary" @click="saveCascaderOptions">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { WidthList, FileLimit, FormatList } from '../../plugins/fields.js'
import { GetSingle } from '../../plugins/utils'
import TitleTips from '../TitleTips'
import CEditor from '../CEditor'

export default {
  name: 'FieldsRight',
  components: {
    TitleTips,
    CEditor
  },
  props: {
    item: {
      default: () => {
        return {}
      },
    },
  },

  inject: ['__TFB__'],

  computed: {
    staticDrageFields () {
      return this.$store.state.contentDrageFields
    },
  },

  data () {
    return {
      widthList: WidthList,
      formatList: FormatList,
      nowItem: {},

      reloadTime: true,
      showImportCascaderDialogFlag: false,

      cascadesString: ''
    }
  },

  watch: {
    '__TFB__.nowDrag': {
      handler (val) {
        this.nowItem = GetSingle(val)
      },
      deep: true,
      immediate: true,
    },

    nowItem: {
      handler (val) {
        this.updateStaticFields(val)
      },
      immediate: true,
      deep: true,
    },
  },

  methods: {
    checkFile (file) {
      const isLt2M =
        file.size / 1024 / 1024 < this.nowItem.settings.limitVolume
      if (!isLt2M) {
        this.$error(
          `上传图片大小不能超过 ${this.nowItem.settings.limitVolume}MB!`
        )
        return
      }
      let tempList = []
      let isName = true

      if (this.nowItem.settings.fileSelects.length) {
        this.nowItem.settings.fileSelects.forEach((item) => {
          let obj = FileLimit.find((row) => row.name == item)
          tempList = [...tempList, ...obj.list]
        })
        const name = file.name.substring(file.name.lastIndexOf('.') + 1)
        isName = tempList.includes(name)
        if (!isName) {
          this.$error(`不支持当前.${name}文件类型!`)
        }
      }

      return isLt2M && isName
    },

    changeMultiple () {
      console.log(this.nowItem)
      this.nowItem.settings.value = this.nowItem.settings.multiple ? [] : ''
    },

    deleteFile (list, index) {
      list.splice(index, 1)
    },

    async uploadSectionFile (data) {
      let formData = new FormData()
      formData.append('file', data.file)
      const res = await targetFlowHttp('manageFlowUpload',formData)
      let obj = {
        uid: data.file.uid,
        name: data.file.name,
        size: data.file.size,
        key: res.key
      }
      this.nowItem.settings.value.push(obj)
    },

    changeText () {},
    swichWidth (item) {
      this.nowItem.settings.width = item
    },
    // 添加选项值
    addOption (list) {
      list.push({ value: list.length, label: '未命名' })
    },

    addCascaderOption () {
      this.cascadesString = JSON.stringify(this.nowItem.settings.cascades, null, '  ')
      this.showImportCascaderDialogFlag = true
    },

    saveCascaderOptions () {
      this.nowItem.settings.cascades = JSON.parse(this.cascadesString)
      this.showImportCascaderDialogFlag = false
    },

    // 删除选项内容
    deleteOption (list, index) {
      list.splice(index, 1)
    },

    // 更新数组中的数据
    updateStaticFields (val) {
      let tempFields = GetSingle(this.staticDrageFields)
      tempFields = tempFields.map((item) => {
        let item1 = item.map((row) => {
          if (this.item.ofdid != this.nowItem.ofdid) {
            if (this.item.ofdid == row.ofdid) {
              let index = row.settings.columns.findIndex(
                (rc) => rc.ofdid == val.ofdid
              )
              row.settings.columns.splice(index, 1, val)
              this.tempNowDrag = row
            }
            return row
          }
          if (row.ofdid == val.ofdid) {
            return val
          }
          return row
        })
        return item1
      })

      this.$store.dispatch(
        'setContentDrageFields',
        GetSingle(tempFields)
      )
    },

    async openFile (item) {
      console.log(item)
      const res = await targetFlowHttp('manageFlowGetPng', '', `?fileUrl=${item.key}`, {isCode: false, method: 'get', responseType:'arraybuffer', isloading: false})
      let blob = new Blob([res.data], {type: 'image/png'})
      let objurl = window.URL.createObjectURL(blob)
      window.open(objurl)
    },
  },
}
</script>

<style lang="less" scoped>
.panel {
  // padding: 12px 16px;
  .block {
    // padding: 12px 12px 16px 12px;
    margin-bottom: 24px;

    .block-file {
      width: 228px;
      height: 32px;
      background: #ffffff;
      border-radius: 3px;
      border: 1px solid #dbdfeb;
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      font-size: 14px;
      padding: 0 12px;
      cursor: pointer;
      &:last-child {
        margin-bottom: 0;
      }

      span {
        margin-left: 8px;
        flex: 1;
      }

      img {
        width: 12px;
        height: 14px;
        cursor: pointer;
      }
    }
  }
  .title {
    font-size: 14px;
    font-weight: 500;
    color: #262a30;
    margin-bottom: 8px;
  }

  .content-row {
    display: flex;
    align-items: center;
    span {
      margin-left: 10px;
      width: 20px;
      font-size: 14px;
      color: #262a30;
      white-space: nowrap;
    }
  }

  .content {
    .options-relative {
      position: relative;
      margin-bottom: 12px;

      &:last-child {
        margin-bottom: 0;
      }

      img {
        position: absolute;
        width: 12px;
        height: 14px;
        right: 10px;
        top: 14px;
        cursor: pointer;
      }
    }

    .auto-select {
      margin-bottom: 12px;
    }

    /deep/ .el-date-editor.el-input {
      width: 100%;
    }
  }

  .content-range {
    display: flex;
    justify-content: space-between;
    align-items: center;

    /deep/ .el-input {
      width: 40%;
    }
    span {
      padding: 0 10px;
    }
  }

  .name {
    font-weight: 500;
    color: #262a30;
    font-size: 16px;
    margin-bottom: 16px;

    img {
      width: 14px;
      height: 14px;
      margin-right: 8px;
    }
  }
}

.fileds-operate {
  // .flex(center, center);
  height: 34px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: #262a30;
  width: 100%;
  margin-bottom: 10px;
  line-height: 34px;
  text-align: center;
  margin-top: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.fileds-operate-before {
  &::before {
    content: "";
    display: block;
    width: 13px;
    height: 13px;
    background: url("../../img/add.png") no-repeat;
    background-size: 100%;
    margin-right: 8px;
  }
}

.row {
  display: flex;
  align-items: center;
  line-height: 36px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;

  .width {
    width: 25%;
    text-align: center;
    border-right: 1px solid #dcdfe6;
    cursor: pointer;
    color: #323d39;
    &:last-child {
      border-right: 0;
    }
  }

  .active {
    background-color: #00ccbf;
    color: #ffffff;
  }
}

:deep .el-cascader--small {
  width: 100%;
}

/deep/ .el-range-editor.el-input__inner {
  width: auto;
}

:deep .el-upload {
  width: 100%;
}
:deep .el-checkbox.is-bordered {
  width: 100%;
}
:deep .el-checkbox.is-bordered + .el-checkbox.is-bordered {
  margin-right: 0;
  margin-left: 0;
}
</style>
